package com.ssb.plugins;

import com.alibaba.fastjson.JSONObject;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.database.datasource.DynamicDataSource;
import com.apache.exception.BusinessException;
import com.apache.ius.plugin.CustomMethodPlugin;
import com.apache.ius.plugin.IusPluginUtil;
import com.apache.tools.DataMap;
import com.apache.tools.StrUtil;
import com.ssb.entity.UserPolicy;
import org.apache.log4j.Logger;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 创建的查询子级渠道商插件
 * @Author IUS platform administrators create generation
 * @Date 2020-1-31 13:51:04
 */
public class ChildBrokerListPluginImpl extends HheSuperPlugin  implements CustomMethodPlugin {
	private Logger log = Logger.getLogger(getClass());
	protected  final static String DATA_SOURCE = DynamicDataSource.getInstance().getDefaultDataSourceKey();
	@Override
	public Object beforeInvoke(Map<String, Object> param) {
		log.info("start->> 执行插件事前方法....");
		//1、校验参数
		String orgId = String.valueOf(param.get("uctUser.w_orgId"));//渠道商ID
		log.info("orgId-->"+orgId);
		if(StrUtil.isNull(orgId)){
			throw new BusinessException("渠道商orgId不能为空");
		}

		//取得此渠道商下的下单的所有子级及投保单量
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT user_id,user_ename,user_cname, count(user_id) policy_num FROM ss_commission_detail");
		sb.append(" WHERE org_id='"+orgId+"'");
		sb.append(" GROUP BY user_id ORDER BY policy_num desc");
		List list = select(sb.toString(),DATA_SOURCE);
		if (list.size() == 0){
            throw new BusinessException("没有下级渠道商或会员！");
        }
		log.info("ss_commission_detail_orgId_list-->"+list.toString());

		Integer brokerTotalPolicyNum = 0;
		Integer mnemberTotalPolicyNum = 0;
		List<Object> resultBrokerList = new ArrayList<>();
		List<Object> resultMemberList = new ArrayList<>();
		List<Object> resultbrokerMemberList = new ArrayList<>();
		StringBuilder userIds = new StringBuilder();
		Map<Object,Object> userPolicyNumMap = new HashMap<Object,Object>();
		//根据USRE_ID 获得各个子级的注册时间
		for(int i=0;i<list.size();i++){
			Map uctUserMap = (Map)list.get(i);
			//拼接userId集
			userIds.append(uctUserMap.get("userId") + ",");
			userPolicyNumMap.put(uctUserMap.get("userId"),uctUserMap.get("policyNum"));
		}
		userIds.deleteCharAt(userIds.length()-1);
		log.info("userIdList-->"+userIds);

		Map selectFrontMap = new HashMap();
		selectFrontMap.put("uctUser.wi_userId",userIds);
		ResultEntity obj = IusPluginUtil.getInstance().select("plateform", "list", "s_uctUser", selectFrontMap);

		if (obj == null || obj.getEntity() == null){
			throw new BusinessException("没有下级渠道商或会员！");
		}

		List userList = (List) obj.getEntity();
		log.info("userList-->"+userList.toString());
		for(int i=0;i<userList.size();i++){
			Map<String,Object> broMemMap = new HashMap<String,Object>();
			UserPolicy userPolicy = new UserPolicy();
			Map uctUserMap = (Map)userList.get(i);

			for (Map.Entry<Object,Object> str : userPolicyNumMap.entrySet()){
				if (str.getKey().equals (uctUserMap.get("userId"))){
					String value = (String) str.getValue();
					userPolicy.setPolicyNum(Integer.parseInt(value));
//					broMemMap.put("policyNum",value);
					break;
				}
			}
//			broMemMap.put("userId",uctUserMap.get("userId"));
//			broMemMap.put("userEname",uctUserMap.get("userEname"));
//			broMemMap.put("userCname",uctUserMap.get("userCname"));
//			broMemMap.put("userType",uctUserMap.get("userType"));
//			broMemMap.put("createTime",uctUserMap.get("createTime"));
			userPolicy.setUserId(String.valueOf(uctUserMap.get("userId")));
			userPolicy.setUserEname(String.valueOf(uctUserMap.get("userEname")));
			userPolicy.setUserCname(String.valueOf(uctUserMap.get("userCname")));
			userPolicy.setUserType(String.valueOf(uctUserMap.get("userType")));
			userPolicy.setCreateTime(String.valueOf(uctUserMap.get("createTime")));
			resultbrokerMemberList.add(userPolicy);

			switch ((String)uctUserMap.get("userType")){
				case "broker": {
//					brokerTotalPolicyNum += Integer.valueOf(String.valueOf(broMemMap.get("policyNum")));
					brokerTotalPolicyNum += Integer.valueOf(String.valueOf(userPolicy.getPolicyNum()));
//					resultBrokerList.add(broMemMap);
				}
				break;
				case "member": {
//					mnemberTotalPolicyNum += Integer.valueOf(String.valueOf(broMemMap.get("policyNum")));
					mnemberTotalPolicyNum += Integer.valueOf(String.valueOf(userPolicy.getPolicyNum()));
//					resultMemberList.add(broMemMap);
				}
				break;
				default:break;
			}
		}
		log.info("resultList-->"+resultBrokerList.toString());
		log.info("resultList-->"+resultMemberList.toString());
		log.info("resultbrokerMemberList-->"+resultbrokerMemberList.toString());

		JSONObject jsonObject = new JSONObject();
		List<UserPolicy> list1 = (List)resultbrokerMemberList;
		jsonObject.put("resultbrokerMemberList",list1.stream().sorted(Comparator.comparing(UserPolicy :: getPolicyNum).reversed()).collect(Collectors.toList()));
//		jsonObject.put("resultBrokerList",resultBrokerList);
//		jsonObject.put("resultMemberList",resultMemberList);
		jsonObject.put("brokerTotalPolicyNum",brokerTotalPolicyNum);
		jsonObject.put("mnemberTotalPolicyNum",mnemberTotalPolicyNum);

		param.put(CustomMethodPlugin.pluginInnerReturn,jsonObject);
		param.put(CustomMethodPlugin.resultMark, "T");
		log.info("end->> 执行插件事前方法....end");
		return param;
	}

	@Override
	public Object doInvoke(Map<String, Object> param) {
		log.info("start->> 执行插件方法....");

		return null;
	}

	@Override
	public Object afterInvoke(Map<String, Object> param) {
		log.info("start->> 执行插件事后方法....");

		return null;
	}

	/**
	 * 规则校验统一入口
	 * @param paramsVo
	 */
	public void run(ParamsVo paramsVo) {
		beforeInvoke(paramsVo.getParams());
	}


}

